package kr.hyosang.util;

import java.io.IOException;
import java.io.InputStream;

public class Util {
    public static String readUtf8Stream(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        byte [] buf = new byte[6];
        int nRead;
        int offset = 0;
        
        while( (nRead = is.read(buf, offset, buf.length - offset)) > 0) {
            nRead += offset; 
            offset = 0;
            for(int i=nRead-2;i<nRead;i++) {
                if(i < 0) continue;
                
                byte c = buf[i];
                
                if( ((c & 0xF8) == 0xF0) ||    /* 네바이트짜리 */
                    (((c & 0xF0) == 0xE0) && (i > 0)) ||    /* 세바이트짜리 */
                    (((c & 0xE0) == 0xC0) && (i > 1)))     /* 두바이트짜리 */
                {
                    offset = nRead - i;
                    break;
                }
            }
            
            sb.append(new String(buf, 0, (nRead - offset)));
            
            //잘린부분 앞으로 복사
            for(int i=0;i<offset;i++) {
                buf[i] = buf[nRead-offset+i];
            }
            
        }
        
        return sb.toString();
        
    }
    
    public static String getRandString(int length) {
        StringBuffer sb = new StringBuffer(length);
        
        /* 범위
         * 0~9 : 48 ~ 57
         * A~Z : 65 ~ 90
         * a~z : 97 ~ 122
         */
        
        int val;
        int cnt = 0;
        char c;
        while(cnt < length) {
            val = (int)(Math.random() * 75) + 48;
            
            if((val >= 48 && val <= 57) ||
               (val >= 65 && val <= 90) ||
               (val >= 97 && val <= 122) ) {
                c = (char)val;
                sb.append(c);
                cnt++;
            }
        }
        
        return sb.toString();
    }
}
